/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ec.cd.server.gui;

import ec.cd.server.ServerBlocking;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;

/**
 *
 * @author endri
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(radioCalibration);
        btnGroup.add(radioNormalRun);
        btnGroup.add(radioPowerSaving);
        ButtonGroup btnGroupSampling = new ButtonGroup();
        btnGroupSampling.add(radioFastest);
        btnGroupSampling.add(radioGame);
        btnGroupSampling.add(radioNormal);
        btnGroupSampling.add(radioUI);
    }

    public void startServer(int testLength, int sendingRate) throws FileNotFoundException, IOException {
        final int length = testLength;
        final int sr = sendingRate;
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                ServerBlocking server;
                int runningMode;
                if (radioCalibration.isSelected()) {
                    runningMode = ServerBlocking.CALIBRATION_RUN;
                } else {
                    runningMode = ServerBlocking.DETECTION_RUN;
                }
                if (runningMode == ServerBlocking.CALIBRATION_RUN) {
                    ServerBlocking.ConfigInfo configInfo = new ServerBlocking.ConfigInfo();
                    configInfo.lengthOfTest = length;
                    server = new ServerBlocking(runningMode, configInfo);

                } else {
                    ServerBlocking.ConfigInfo configInfo = new ServerBlocking.ConfigInfo();
                    //read the data from the files
                    readRanges(configInfo);
                    if (radioFastest.isSelected()) {
                        configInfo.samplingRate = 0;
                    }
                    if (radioGame.isSelected()) {
                        configInfo.samplingRate = 1;
                    }
                    if (radioUI.isSelected()) {
                        configInfo.samplingRate = 2;
                    }
                    if (radioNormal.isSelected()) {
                        configInfo.samplingRate = 3;
                    }
                    configInfo.sendingRate = sr;
                    server = new ServerBlocking(runningMode, configInfo);
                }
                try {
                    server.startListening();
                } catch (IOException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                    ex.printStackTrace();
                }
            }
        });
        t.start();

    }

    private void readRanges(ServerBlocking.ConfigInfo configInfo) {
        try {
            FileReader fileReaderAccTorso = new FileReader("accRangesTorso.txt");
            FileReader fileReaderGyrTorso = new FileReader("gyrRangesTorso.txt");
            BufferedReader readerAccTorso = new BufferedReader(fileReaderAccTorso);
            BufferedReader readerGyrTorso = new BufferedReader(fileReaderGyrTorso);
            FileReader fileReaderAccArm = new FileReader("accRangesArm.txt");
            FileReader fileReaderGyrArm = new FileReader("gyrRangesArm.txt");
            BufferedReader readerAccArm = new BufferedReader(fileReaderAccArm);
            BufferedReader readerGyrArm = new BufferedReader(fileReaderGyrArm);
            FileReader fileReaderAccLeg = new FileReader("accRangesLeg.txt");
            FileReader fileReaderGyrLeg = new FileReader("gyrRangesLeg.txt");
            BufferedReader readerAccLeg = new BufferedReader(fileReaderAccLeg);
            BufferedReader readerGyrLeg = new BufferedReader(fileReaderGyrLeg);
            configInfo.accRangesTorso = readRange(readerAccTorso);
            configInfo.gyrRangesTorso = readRange(readerGyrTorso);
            configInfo.accRangesArm = readRange(readerAccArm);
            configInfo.gyrRangesArm = readRange(readerGyrArm);
            configInfo.accRangesLeg = readRange(readerAccLeg);
            configInfo.gyrRangesLeg = readRange(readerGyrLeg);
            readerAccArm.close();
            readerAccLeg.close();
            readerAccTorso.close();
            readerGyrArm.close();
            readerGyrLeg.close();
            readerGyrTorso.close();
            fileReaderAccArm.close();
            fileReaderAccLeg.close();
            fileReaderAccTorso.close();
            fileReaderGyrArm.close();
            fileReaderGyrLeg.close();
            fileReaderGyrTorso.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "The ranges could not be found or could not be read.");
            ex.printStackTrace();
        }

    }

    private float[] readRange(BufferedReader bufferedReader) throws IOException {
        float[] range = new float[18];
        String line;
        int i = 0;
        while ((line = bufferedReader.readLine()) != null) {
            String[] tockens = line.split(", ");
            for (String s : tockens) {
                try {
                    float f = Float.parseFloat(s);
                    range[i] = f;
                } catch (Exception ex) {
                }
            }
        }
        return range;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtTestLength = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        btnRun = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txtSendingRate = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        radioFastest = new javax.swing.JRadioButton();
        radioGame = new javax.swing.JRadioButton();
        radioUI = new javax.swing.JRadioButton();
        radioNormal = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        radioCalibration = new javax.swing.JRadioButton();
        radioNormalRun = new javax.swing.JRadioButton();
        radioPowerSaving = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Length of the test:");

        jLabel2.setText("messages");
        jLabel2.setToolTipText("");

        btnRun.setText("Run");
        btnRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRunActionPerformed(evt);
            }
        });

        jLabel4.setText("Sending Rate:");

        jLabel5.setText("ms");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Sampling Rate"));

        radioFastest.setText("Fastest");

        radioGame.setText("Game");

        radioUI.setText("UI");

        radioNormal.setSelected(true);
        radioNormal.setText("Normal");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioFastest)
                    .addComponent(radioGame)
                    .addComponent(radioUI)
                    .addComponent(radioNormal))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(radioFastest)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioGame)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioUI)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(radioNormal))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Running Mode"));

        radioCalibration.setSelected(true);
        radioCalibration.setText("Calibration Run");

        radioNormalRun.setText("Normal Run");

        radioPowerSaving.setText("Power Saving Run");
        radioPowerSaving.setToolTipText("Sending values when they cross ranges only");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(radioCalibration)
                .addGap(18, 18, 18))
            .addComponent(radioNormalRun)
            .addComponent(radioPowerSaving)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(radioCalibration)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioNormalRun)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioPowerSaving)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtSendingRate, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtTestLength, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnRun, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(btnRun, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTestLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(2, 2, 2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtSendingRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRunActionPerformed
        // TODO add your handling code here:
        int length = 0, rate = 0;
        try {
            length = Integer.parseInt(txtTestLength.getText());
            rate = Integer.parseInt(txtSendingRate.getText());
            this.setVisible(false);
            JOptionPane.showMessageDialog(this, "Close this to start waiting for clients to connect.");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Check the input. Please enter only integers.");
        }
        try {
            startServer(length, rate);
        } catch (Exception ex) {
            System.out.println("The server crashed:");
            ex.printStackTrace();
            System.exit(1);
        }
    }//GEN-LAST:event_btnRunActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRun;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton radioCalibration;
    private javax.swing.JRadioButton radioFastest;
    private javax.swing.JRadioButton radioGame;
    private javax.swing.JRadioButton radioNormal;
    private javax.swing.JRadioButton radioNormalRun;
    private javax.swing.JRadioButton radioPowerSaving;
    private javax.swing.JRadioButton radioUI;
    private javax.swing.JTextField txtSendingRate;
    private javax.swing.JTextField txtTestLength;
    // End of variables declaration//GEN-END:variables
}
